package com.shuangseqiu.controller;

import com.shuangseqiu.service.Cz89AnalysisService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * cz89网站分析控制器，提供HTTP API接口
 */
@RestController
@RequestMapping("/api/cz89")
public class Cz89Controller {

    private static final Logger logger = LoggerFactory.getLogger(Cz89Controller.class);

    @Autowired
    private Cz89AnalysisService cz89AnalysisService;

    /**
     * 根据预测期数分析cz89网站的彩票预测文章
     *
     * @param period 预测期数
     * @return 分析结果
     */
    @GetMapping("/analyze/{period}")
    public ResponseEntity<?> analyzeByPeriod(@PathVariable("period") String period) {
        try {
            // 验证期数格式
            if (!isValidPeriod(period)) {
                return ResponseEntity.badRequest().body("无效的期数格式，请提供有效的预测期数");
            }

            logger.info("接收到cz89网站分析请求，预测期数: {}", period);

            // 调用服务层进行分析
            Map<String, Object> result = cz89AnalysisService.analyzeByPeriod(period);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            logger.error("cz89网站分析请求处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 批量分析多个期数的预测文章
     *
     * @param requestBody 包含期数列表的请求体
     * @return 综合分析结果
     */
    @PostMapping("/analyze-batch")
    public ResponseEntity<?> analyzeBatchPeriods(@RequestBody Map<String, String[]> requestBody) {
        try {
            String[] periods = requestBody.get("periods");

            if (periods == null || periods.length == 0) {
                return ResponseEntity.badRequest().body("期数列表不能为空");
            }

            logger.info("接收到批量分析请求，共 {} 个期数", periods.length);

            // 验证所有期数格式
            for (String period : periods) {
                if (!isValidPeriod(period)) {
                    return ResponseEntity.badRequest().body("无效的期数格式: " + period);
                }
            }

            // 存储各个期数的分析结果
            Map<String, Object> overallResult = new HashMap<>();
            Map<String, Object> individualResults = new HashMap<>();
            int successCount = 0;

            for (String period : periods) {
                try {
                    Map<String, Object> result = cz89AnalysisService.analyzeByPeriod(period);
                    individualResults.put(period, result);
                    if (Boolean.TRUE.equals(result.get("success"))) {
                        successCount++;
                    }
                } catch (Exception e) {
                    logger.error("分析期数 {} 失败", period, e);
                    Map<String, Object> errorResult = new HashMap<>();
                    errorResult.put("success", false);
                    errorResult.put("error", e.getMessage());
                    individualResults.put(period, errorResult);
                }
            }

            overallResult.put("totalPeriods", periods.length);
            overallResult.put("successCount", successCount);
            overallResult.put("results", individualResults);

            return ResponseEntity.ok(overallResult);

        } catch (Exception e) {
            logger.error("批量分析请求处理失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("error", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 验证期数格式是否有效
     *
     * @param period 期数字符串
     * @return 是否有效
     */
    private boolean isValidPeriod(String period) {
        // 期数通常为数字，长度在5-8位之间
        return period != null && period.matches("\\d{5,8}");
    }

    /**
     * 健康检查端点
     */
    @GetMapping("/health")
    public ResponseEntity<?> healthCheck() {
        Map<String, Object> response = new HashMap<>();
        response.put("status", "UP");
        response.put("message", "cz89网站分析服务运行正常");
        return ResponseEntity.ok(response);
    }
}